package com.ywgt;

public class CirleLinkedList {
    public static void main(String[] args) {
        CirleList cirleList=new CirleList();
        CirleNode cirleNode = cirleList.getCirleNode();
        cirleList.add(4000);
        cirleList.print();
        cirleList.remove(1,4000,997);
    }
}

class CirleList{
    //CirleNode cirleNode=new CirleNode(0);
    CirleNode cirleNode=null;
    CirleNode cur=null;
    public CirleNode getCirleNode() {
        return cirleNode;
    }
    CirleNode first;
//    public void add(CirleNode node){
//        CirleNode cur=first;
//        while(cur.next!=first){
//            cur=cur.next;
//        }
//        cur.next=node;
//        node.next=first;
//    }
//
    public void add(int nums){
        for (int i = 1; i <=nums; i++) {
            CirleNode cirleNode=new CirleNode(i);
            if(i==1){
                first=cirleNode;
                cirleNode.next=first;
                cur=first;
            }else {
                cur.next=cirleNode;
                cirleNode.next=first;
                cur=cur.next;
            }
        }

    }
    public void print(){
        cur=first;
        while(true){
            System.out.println(cur);
            if(cur.next==first){
                break;
            }
            cur=cur.next;
        }
    }

    /**
     *
     * @param no 从第几个小孩开始
     * @param nums 一共多少个小孩
     * @param m 每次数几个数
     */
    public void remove(int no,int nums,int m){
        if(no<1||no>nums||first==null){
            return;
        }
        //辅助指针 指向first的前一个位置
        CirleNode helper=first;
        while(true){
            if(helper.next==first){
                break;
            }
            helper=helper.next;
        }
        while(nums>1) {
            for (int i = 1; i < m; i++) {
                first=first.next;
                helper=helper.next;
            }
            first=first.next;
            helper.next=first;
            nums--;
        }

        System.out.println(first);
        System.out.println(helper);
        print();
    }
}

class CirleNode{
    int no;
    CirleNode next;

    public CirleNode(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "CirleNode{" +
                "no=" + no +
                '}';
    }
}
